package com.education.teach.mvp.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

import com.dn.res.wideget.DnToolbar;
import com.education.teach.R;
import com.education.teach.di.component.DaggerAddCounselComponent;
import com.education.teach.di.module.AddCounselModule;
import com.education.teach.mvp.contract.AddCounselContract;
import com.education.teach.mvp.model.bean.AddCounselBean;
import com.education.teach.mvp.model.bean.LoginBean;
import com.education.teach.mvp.model.service.ApiService;
import com.education.teach.mvp.presenter.AddCounselPresenter;
import com.education.teach.mvp.ui.adapter.AddCounselAdapter;
import com.education.teach.utils.DnCommonUtils;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.integration.IRepositoryManager;
import com.jess.arms.utils.ArmsUtils;

import org.simple.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import butterknife.BindView;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import me.jessyan.rxerrorhandler.core.RxErrorHandler;
import me.jessyan.rxerrorhandler.handler.ErrorHandleSubscriber;

import static com.jess.arms.utils.Preconditions.checkNotNull;


public class AddCounselActivity extends BaseActivity<AddCounselPresenter> implements AddCounselContract.View {

    @BindView(R.id.sp_teacher)
    Spinner sp_teacher;
    @BindView(R.id.toolbar)
    DnToolbar mToolbar;
    @BindView(R.id.lv_content)
    RecyclerView mRecyclerView;
    @BindView(R.id.btn_QA)
    Button btn_QA;
    @BindView(R.id.et_text)
    EditText et_text;
    int maxRow = 10;
    int page = 1;
    private LoginBean mLoginBean;
    private List<AddCounselBean.ResultBean> mList = new ArrayList<>();
    private AddCounselAdapter mAdapter;
    private ArrayList<String> teacherListId = new ArrayList<String>();
    private String selected;
    @Inject
    IRepositoryManager mIRepositoryManager;
    @Inject
    RxErrorHandler mRxErrorHandler;

    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        DaggerAddCounselComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .addCounselModule(new AddCounselModule(this))
                .build()
                .inject(this);
    }

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        return R.layout.activity_add_counsel; //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        mToolbar.setMainTitle("发起疑问");
        mToolbar.setToolbarLeftBackImageRes(R.mipmap.top_back);
        mToolbar.setOnLeftTitleClickListener(view -> finish());

        mLoginBean = DnCommonUtils.getUserModel(this);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mAdapter = new AddCounselAdapter(R.layout.item_add_counsel, mList);
        mRecyclerView.setAdapter(mAdapter);

        getData();

        btn_QA.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String question = et_text.getText().toString();
                if ("".equals(question)) {
                    showMessage("请填写问题");
                } else {
                    Map<String, String> map = new HashMap<>();
                    LoginBean bean = DnCommonUtils.getUserModel(AddCounselActivity.this);
                    map.put("jsId", selected);
                    map.put("yhxlh", bean.getResult().getXlh());
                    map.put("yhmc", bean.getResult().getYhmc());
                    map.put("content", question);

                    mIRepositoryManager
                            .obtainRetrofitService(ApiService.class)
                            .addConsultationQuestion(map)
                            .subscribeOn(Schedulers.io())
                            .observeOn(AndroidSchedulers.mainThread())
                            .subscribe(new ErrorHandleSubscriber<AddCounselBean>(mRxErrorHandler) {
                                @Override
                                public void onNext(AddCounselBean addCounselBean) {
                                    EventBus.getDefault().post("refresh", "DO_REFRESH");
                                    showMessage("提问已经提交给老师，请等待答复。");
                                    finish();
                                }
                            });
                }
            }
        });


    }

    class spinner2Listener implements android.widget.AdapterView.OnItemSelectedListener {


        @Override
        public void onItemSelected(AdapterView<?> parent, View view,
                                   int position, long id) {
//            String selected = parent.getItemAtPosition(position).toString();
            selected = teacherListId.get(position).toString();
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {
            System.out.println("nothingSelect");
        }
    }

    private void getData() {

        Map<String, String> map = new HashMap<>();
        LoginBean bean = DnCommonUtils.getUserModel(this);
        map.put("banjiId", bean.getResult().getClazzIdList().get(0));// banjiId是登录里的clazzid
        mIRepositoryManager
                .obtainRetrofitService(ApiService.class)
                .getTeacher(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new ErrorHandleSubscriber<AddCounselBean>(mRxErrorHandler) {
                    @Override
                    public void onNext(AddCounselBean addCounselBean) {
                        mAdapter.setNewData(addCounselBean.getResult());
                        mList = addCounselBean.getResult();
                        ArrayList<String> teacherList = new ArrayList<String>();
//                        teacherList.add("请选择您要提问的老师");
//                        teacherListId.add("");
                        for (int i = 0; i < mList.size(); i++) {
                            AddCounselBean.ResultBean bean = mList.get(i);
                            teacherList.add(bean.getJiaoshiName());
                            teacherListId.add(bean.getJiaoshiSign());
                        }
                        ArrayAdapter adapter2 = new ArrayAdapter(AddCounselActivity.this, R.layout.item_teacher, R.id.tv_teacher, teacherList);
                        sp_teacher.setAdapter(adapter2);
                        sp_teacher.setOnItemSelectedListener(new spinner2Listener());
                    }
                });
    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.makeText(this, message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        finish();
    }

}
